package cn.lkp.controller;

import cn.lkp.bean.Hyperlinks;
import cn.lkp.bean.Resset;
import cn.lkp.dao.HyperlinksMapper;
import cn.lkp.service.LinkService;
import cn.lkp.service.RessetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class LinkController {

    @Autowired
    HyperlinksMapper mapper;

    @Autowired
    private LinkService linkService;

    @Autowired
    private RessetService ressetService;

    @RequestMapping(value = "/admin/addlinks", method = RequestMethod.GET)
    public String toAddLinks() {
        return "pages/addLinks";
    }


    @RequestMapping(value = "/admin/insertlink", method = RequestMethod.POST)
    public String insertAddLinks
            (@RequestParam(required = false) String linkurl, @RequestParam(required = false) String linktitle,
             @RequestParam(required = false) String linkdesc, @RequestParam(required = false) String linkimage) {
        // 检测参数的合法性
        if (linkurl == null) {
            linkurl = "";
        }
        if (linktitle == null) {
            linktitle = "";
        }
        if (linkdesc == null) {
            linkdesc = "";
        }
        if (linkimage == null) {
            linkimage = "";
        }
        // 先将记录插入超链接表，然后再将返回的id插入资源集表中
        Hyperlinks link = new Hyperlinks();
        link.setLinkUrl(linkurl);
        link.setLinkTitle(linktitle);
        link.setLinkDescription(linkdesc);
        link.setLinkImage(linkimage);
        linkService.Add(link);
        int id = link.getLinkId();

        Resset resset = new Resset();
        resset.setSetType("hyperlink");
        resset.setSetName("project-hyperlink");
        resset.setIdInType(id);
        ressetService.Add(resset);

        return "pages/addLinks";
    }

    @RequestMapping(value = "/admin/displaylinks", method = RequestMethod.GET)
    public String displayLinks(Model model) {

        List<Resset> resset = ressetService.getResourcesId("project-hyperlink");
        List<Hyperlinks> links = linkService.getList(resset);
        // 将值传给前端
        model.addAttribute("linklist", links);
        return "pages/displayLinks";
    }


    // 删除一条链接信息
    @RequestMapping(value = "/admin/deletelink", method = RequestMethod.GET)
    public String deleteLink(@RequestParam String id) {
        int linkid = Integer.parseInt(id);
        linkService.deleteById(linkid);
        return "redirect:/admin/displaylinks";
    }




}
